package com.supersit.greensproject.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.andview.refreshview.XRefreshView;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.adapter.MaketSubjectDataAdapter;
import com.supersit.greensproject.entity.MaketSubject;
import com.supersit.greensproject.resources.Resources;
import com.supersit.greensproject.utils.KeyBoardUtils;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.CustomDialog;
import com.supersit.greensproject.view.MyTitleBar;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cong on 2016/7/15.
 */
@ContentView(R.layout.activity_query_subject_data)
public class QueryMaketSubjectDataActivity extends BaseActivity {
    private Context context;
    private MyTitleBar myTitleBar;
    private CustomDialog dialog;
    private int maketType = -1;
    @ViewInject(R.id.et_search_key_word)
    private EditText etSearchKeyWord;
    @ViewInject(R.id.sp_subject_select_area)
    private Spinner spArea;
    @ViewInject(R.id.lv_maket_subject_list)
    private ListView lvMaketList;
    @ViewInject(R.id.custom_view)
    private XRefreshView refreshView;
    @ViewInject(R.id.ib_search_icon_bt)
    private ImageButton ibSearch;
    private MaketSubjectDataAdapter maketSubjectAdapter;
    private List<MaketSubject> maketSubjectList;
    public static long lastRefreshTime;
    //每页查询的数量
    private final int selectCount = 20;
    //每页查询的开始条数
    private int selectStartNum = 0;
    private DbManager db;
    private int areaPosition;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = this;
        setTitlebar();
        initVariable();
        bindListener();
    }

    private void setTitlebar() {
        myTitleBar = new MyTitleBar(context, findViewById(R.id.query_subject_data_title));
        myTitleBar.setTitleText(Resources.subjectBaseTitles[5]);
        myTitleBar.setChildVisibility(false, myTitleBar.getmImgRight());
        myTitleBar.showRightText();
    }

    private void bindListener() {
        myTitleBar.setImg1Listener(onClickListener);
        myTitleBar.setImgRightlistener(onClickListener);
        lvMaketList.setOnItemClickListener(onItemClickListener);
        ibSearch.setOnClickListener(onClickListener);
        refreshView.setXRefreshViewListener(simpleXRefreshListener);
        spArea.setOnItemSelectedListener(onItemSelectedListener);
        lvMaketList.setOnItemLongClickListener(onItemLongClickListener);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.title_bar_left:
                    finish();
                    break;
                case R.id.title_right_text:
                    View view = LayoutInflater.from(context).inflate(R.layout.radiogroup_maket_selected, null);
                    final RadioGroup rg = (RadioGroup) view.findViewById(R.id.rg_maket_type);
                    RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            Intent intent = new Intent(context, MaketSubjectEnteringActivity.class);
                            intent.putExtra("maketFlag", 0);
                            switch (checkedId) {
                                case R.id.rb_wholesale_maket:
                                    maketType = 0;
                                    intent.putExtra("maketType", maketType);
                                    startActivity(intent);
                                    dialog.dismiss();
                                    break;
                                case R.id.rb_retail_maket:
                                    maketType = 1;
                                    intent.putExtra("maketType", maketType);
                                    startActivity(intent);
                                    dialog.dismiss();
                                    break;
                            }
                        }
                    };
                    rg.setOnCheckedChangeListener(onCheckedChangeListener);
                    CustomDialog.Builder customBuilder = new CustomDialog.Builder(
                            context);
                    customBuilder
                            .setTitle(R.string.select_maket_hint)
                            .setContentView(view)
                            .setNegativeButton(null,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.dismiss();
                                        }
                                    })
                            .setPositiveButton(null,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.dismiss();
                                        }
                                    });
                    dialog = customBuilder.create();
                    dialog.show();
                    break;
                case R.id.ib_search_icon_bt:
                    if (!TextUtils.isEmpty(etSearchKeyWord.getText().toString().trim())) {
                        String searchKey = etSearchKeyWord.getText().toString().trim();
                        if (null != maketSubjectList)
                            maketSubjectList.clear();
                        selectStartNum = 0;
                        setRefreshViewOperate(false);
                        try {
                            maketSubjectList = db.selector(MaketSubject.class).where("maketName", "like", "%" + searchKey + "%").and("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                            if (maketSubjectList.size() != 0) {
                                maketSubjectAdapter.setData(maketSubjectList);
                                maketSubjectAdapter.notifyDataSetChanged();
                            } else {
                                T.showShort(context, String.format(context.getResources().getString(R.string.serch_not_result_for_maket), searchKey));
                                maketSubjectAdapter.setData(maketSubjectList);
                                maketSubjectAdapter.notifyDataSetChanged();
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            selectStartNum = 0;
                            //setRefreshViewOperate(true);
                            maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                            maketSubjectAdapter.setData(maketSubjectList);
                            maketSubjectAdapter.notifyDataSetChanged();
                            spArea.setSelection(0);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                //  startActivity(new Intent(context,MaketSubjectEnteringActivity.class));
            }
        }
    };

    private void initVariable() {
        KeyBoardUtils.closeKeybord(etSearchKeyWord, context);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                context, R.array.base_area, R.layout.spinner_text);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spArea.setAdapter(adapter);
        db = db = XUtilsDbManager.getInstance();
        setRefreshViewOperate(true);
        maketSubjectList = new ArrayList<MaketSubject>();
        try {
            maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        maketSubjectAdapter = new MaketSubjectDataAdapter(context, maketSubjectList);
        lvMaketList.setAdapter(maketSubjectAdapter);
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(context, MaketSubjectEnteringActivity.class);
            int x = maketSubjectList.size();
            intent.putExtra("maketFlag", 1);
            Bundle bundle = new Bundle();
            bundle.putSerializable("maketsubject", maketSubjectList.get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };

    private void setRefreshViewOperate(boolean flag) {

        if (flag) {
            // 设置是否可以下拉刷新
            if (!refreshView.getPullRefreshEnable()) {
                refreshView.setPullRefreshEnable(true);
            }
            // 设置是否可以上拉加载
            if (!refreshView.getPullLoadEnable()) {
                refreshView.setPullLoadEnable(true);
            }
        } else {
            if (refreshView.getPullRefreshEnable()) {
                refreshView.setPullRefreshEnable(false);
            }
            if (refreshView.getPullLoadEnable()) {
                refreshView.setPullLoadEnable(false);
            }
        }
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);
        // 设置时候可以自动刷新
        refreshView.setAutoRefresh(false);
    }

    private XRefreshView.SimpleXRefreshListener simpleXRefreshListener = new XRefreshView.SimpleXRefreshListener() {
        @Override
        public void onLoadMore(boolean isSilence) {
            super.onLoadMore(isSilence);
            selectStartNum += 20;
            if (0 == areaPosition) {
                try {
                    List<MaketSubject> newData = db.selector(MaketSubject.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (newData.size() > 0) {
                        maketSubjectList.addAll(newData);
                        if (null != maketSubjectList)
                            maketSubjectAdapter.setData(maketSubjectList);
                        maketSubjectAdapter.notifyDataSetChanged();
                    } else {
                        T.showShort(context, R.string.next_is_null);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    List<MaketSubject> newData = db.selector(MaketSubject.class).where("isDelete", "=", 1).and("areaId", "=", areaPosition - 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (newData.size() != 0) {
                        maketSubjectList.addAll(newData);
                        if (null != maketSubjectList)
                            maketSubjectAdapter.setData(maketSubjectList);
                        maketSubjectAdapter.notifyDataSetChanged();
                    } else {
                        T.showShort(context, R.string.next_is_null);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            refreshView.stopLoadMore();
        }

        @Override
        public void onRefresh() {
            super.onRefresh();
            if (null != maketSubjectList)
                maketSubjectList.clear();
            selectStartNum = 0;
            if (0 == areaPosition) {
                try {
                    maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != maketSubjectList) {
                        maketSubjectAdapter.setData(maketSubjectList);
                        maketSubjectAdapter.notifyDataSetChanged();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {
                selectStartNum = 0;
                try {
                    maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).and("areaId", "=", areaPosition - 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != maketSubjectList) {
                        maketSubjectAdapter.setData(maketSubjectList);
                        maketSubjectAdapter.notifyDataSetChanged();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            refreshView.stopRefresh();
        }
    };
    private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            areaPosition = position;
            if (null != maketSubjectList)
                maketSubjectList.clear();
            selectStartNum = 0;
            setRefreshViewOperate(true);
            if (0 == position) {
                try {
                    maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != maketSubjectList)
                        maketSubjectAdapter.setData(maketSubjectList);
                    maketSubjectAdapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).and("areaId", "=", areaPosition - 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != maketSubjectList)
                        maketSubjectAdapter.setData(maketSubjectList);
                    maketSubjectAdapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    @Override
    public void onResume() {
        super.onResume();
        spArea.setSelection(0);
        setRefreshViewOperate(true);
        selectStartNum = 0;
        try {
            maketSubjectList = db.selector(MaketSubject.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
            if (null != maketSubjectList && maketSubjectList.size() > 0)
                maketSubjectAdapter.setData(maketSubjectList);
            maketSubjectAdapter.notifyDataSetChanged();
            etSearchKeyWord.setText("");
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private AdapterView.OnItemLongClickListener onItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int postion, long l) {
            CustomDialog dialog;
            CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
            customBuilder.setTitle(R.string.custom_dialog_maket_title);
            customBuilder.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    MaketSubject ms = maketSubjectList.get(postion);
                    ms.setOperationsTatus(0);
                    try {
                        db.update(ms, "operationsTatus");
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    T.showShort(context, R.string.synchorization_update_delete);
                    dialogInterface.dismiss();
                    onResume();
                }
            });
            customBuilder.setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            dialog = customBuilder.create();
            dialog.show();
            return true;
        }
    };
}
